import {
  Radio,
  Button,
  Typography,
  Form,
  DatePicker,
  Tooltip,
  message,
  notification,
  Input,
  Table,
} from "antd";
import {
  QuestionCircleOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
} from "@ant-design/icons";
import moment from "moment";
import operationsDesc from "../../common/operation";
import { formatFileSize } from "../../common/util";
import operationError from "../../common/error";
import "./index.scss";

const { remote, ipcRenderer, shell } = window.electron;
const config = remote.getGlobal("config");
const { dialog } = remote;
const currentWindow = remote.getCurrentWindow();

const labelCol = { sm: { span: 8 }, md: { span: 4 } };
const wrapperCol = { sm: { span: 16 }, md: { span: 20 } };
const buttonWrapperCol = {
  sm: { offset: 8, span: 16 },
  md: { offset: 4, span: 20 },
};
const timeFormat = "Y-MM-DD-HH-00-00";
const increasedColor = { color: "#3f8600" };
const reducedColor = { color: "#cf1322" };

export default class MainContent extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      local: config.local || {},
      readWay: config.readWay || "local",
      prefix: config.prefix || "",
      startTime: moment().subtract(7, "days").format(timeFormat),
      endTime: moment().format(timeFormat),
      selectedTime: 7,
      loading: false,
      handleWay: "user",
      result: [],
    };
  }

  componentDidMount() {
    ipcRenderer.on("showResultData", (event, res) => {
      if (res.status === 2) {
        notification.error({ message: "系统出错了", description: res.message });
      } else if (res.status === 1) {
        notification.warning({ message: "信息错误", description: res.message });
      } else {
        notification.success({ message: "读取成功", description: res.message });
      }
      // console.log("res:", res);

      this.setState({ loading: false, result: Object.values(res.data || {}) });
    });
  }

  handleStatistics = () => {
    const {
      local,
      readWay,
      startTime,
      endTime,
      handleWay,
      prefix,
    } = this.state;
    if (!startTime || !endTime) {
      message.warning("请选择统计事件段");
      return;
    }
    if (readWay === "local" && !local.dir) {
      message.warning("请选择日志所在位置");
      return;
    }
    if (
      readWay === "client" &&
      (!config.connection || Object.keys(config.connection).length === 0)
    ) {
      message.warning("请先输入登录信息");
      return;
    }
    this.setState({ loading: true });
    // 保存日志文件的前缀信息
    ipcRenderer.sendSync("setConfig", { local, prefix });
    ipcRenderer.send("handleStatistics", {
      readWay,
      startTime,
      endTime,
      handleWay,
    });
    // const res = ipcRenderer.sendSync("handleStatistics", {
    //   readWay,
    //   startTime,
    //   endTime,
    //   handleWay,
    // });
    // if (res.status === 2) {
    //   notification.error({ message: "系统出错了", description: res.message });
    // } else if (res.status === 1) {
    //   notification.warning({ message: "信息错误", description: res.message });
    // } else {
    //   notification.success({ message: "读取成功", description: res.message });
    // }
    // // console.log("res:", res);

    // this.setState({ loading: false, result: Object.values(res.data || {}) });
  };

  getColumns = () => {
    return [
      { title: "用户", dataIndex: "name", key: "name" },
      {
        title: "请求操作",
        dataIndex: "operations",
        key: "operations",
        render: (operations) => (
          <ul>
            {Object.keys(operations).map((operation) => (
              <li key={Math.random()}>
                <Tooltip title={operationsDesc[operation]}>
                  <Typography.Text strong>{operation}: </Typography.Text>
                </Tooltip>
                {operations[operation]} 次
              </li>
            ))}
          </ul>
        ),
      },
      {
        title: "空间占用",
        dataIndex: "size",
        key: "size",
        render: (_, record) => (
          <div>
            <div style={increasedColor}>
              <ArrowUpOutlined style={increasedColor} />
              {" " + formatFileSize(record.increasedSize)}
            </div>
            <div style={reducedColor}>
              <ArrowDownOutlined style={reducedColor} />
              {" " + formatFileSize(record.reducedSize)}
            </div>
          </div>
        ),
      },
      {
        title: "外网流量",
        dataIndex: "outTraffic",
        key: "outTraffic",
        render: (traffic) => formatFileSize(traffic),
      },
      {
        title: "失败的请求",
        dataIndex: "errors",
        key: "errors",
        render: (errors) => (
          <ul>
            {Object.keys(errors).map((err) => (
              <li key={Math.random()}>
                <Tooltip title={operationsDesc[err]}>
                  <Typography.Text strong>{err}: </Typography.Text>
                </Tooltip>
                {Object.values(errors[err]).reduce((i, t) => i + t, 0)} 次
                <Tooltip
                  title={
                    <div>
                      {Object.keys(errors[err]).map(
                        (reason) =>
                          (operationError[reason]
                            ? operationError[reason].messageCN
                            : "未知错误" + reason) +
                          ": " +
                          errors[err][reason] +
                          " 次"
                      )}
                    </div>
                  }
                >
                  {" "}
                  <QuestionCircleOutlined />
                </Tooltip>
              </li>
            ))}
          </ul>
        ),
      },
    ];
  };

  showConnect = () => {
    ipcRenderer.send("showConnect");
  };

  chooseDir = () => {
    const { local } = this.state;
    dialog
      .showOpenDialog(currentWindow, {
        title: "选择日志文件所在文件夹",
        properties: ["openDirectory"],
      })
      .then((res) => {
        if (!res.canceled && res.filePaths.length > 0) {
          local.dir = res.filePaths[0];
          this.setState({ local: { ...local } });
          ipcRenderer.send("setConfig", { local });
        }
      })
      .catch((err) => {
        notification.error(JSON.stringify(err));
      });
  };

  changeRangeTime = (rangeTime) => {
    this.setState({
      selectedTime: 0,
      startTime: rangeTime[0].format(timeFormat),
      endTime: rangeTime[1].format(timeFormat),
    });
  };

  changeFilterTime = (value) => {
    this.setState({
      selectedTime: value,
      startTime: moment().subtract(value, "days").format(timeFormat),
      endTime: moment().format(timeFormat),
    });
  };

  getTimeTooltip = () => {
    return (
      <span>
        选择时间段{" "}
        <Tooltip
          title="根据阿里云日志文件命名规则筛选分析文件"
          overlayStyle={{ wordBreak: "break-all" }}
        >
          <QuestionCircleOutlined />
        </Tooltip>
      </span>
    );
  };

  render() {
    const {
      readWay,
      local,
      selectedTime,
      loading,
      handleWay,
      result,
      prefix,
    } = this.state;
    return (
      <div className="container">
        <div className="radio-center">
          <Radio.Group
            value={readWay}
            buttonStyle="solid"
            onChange={(e) => this.setState({ readWay: e.target.value })}
          >
            <Radio.Button value="local">本地日志文件</Radio.Button>
            <Radio.Button value="client">联网查询日志文件</Radio.Button>
          </Radio.Group>
        </div>
        {readWay === "local" && (
          <Form.Item
            label="日志所在位置"
            labelCol={labelCol}
            wrapperCol={wrapperCol}
            required
          >
            <Button type="primary" onClick={this.chooseDir}>
              选择本地日志所在文件夹
            </Button>
            {local.dir && (
              <Button type="link">
                <Typography.Paragraph copyable>
                  <span onClick={() => shell.showItemInFolder(local.dir)}>
                    {local.dir}
                  </span>
                </Typography.Paragraph>
              </Button>
            )}
          </Form.Item>
        )}
        {readWay === "client" && (
          <Form.Item
            label="登录信息"
            labelCol={labelCol}
            wrapperCol={wrapperCol}
            required
          >
            <Button type="primary" onClick={this.showConnect}>
              输入OSS登录信息
            </Button>
            <span style={{ marginLeft: 8 }}>
              {config.connection ? config.connection.endpoint : ""}
            </span>
          </Form.Item>
        )}
        <Form.Item
          label="日志文件前缀"
          labelCol={labelCol}
          wrapperCol={wrapperCol}
        >
          <Input
            value={prefix}
            onChange={(e) => this.setState({ prefix: e.target.value })}
            placeholder="请填写本地日志文件的前缀"
          />
        </Form.Item>
        <Form.Item
          label={this.getTimeTooltip()}
          labelCol={labelCol}
          wrapperCol={wrapperCol}
          required
        >
          <Radio.Group
            value={selectedTime}
            onChange={(e) => this.changeFilterTime(e.target.value)}
          >
            <Radio value={1}>最近一天</Radio>
            <Radio value={3}>最近三天</Radio>
            <Radio value={7}>最近一周</Radio>
            <Radio value={0}>
              <DatePicker.RangePicker
                disabledDate={(current) => current > moment().endOf("day")}
                showTime
                format="YYYY-MM-DD HH:00:00"
                onChange={this.changeRangeTime}
              />
            </Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="统计方式"
          labelCol={labelCol}
          wrapperCol={wrapperCol}
          required
        >
          <Radio.Group
            value={handleWay}
            onChange={(e) => this.setState({ handleWay: e.target.value })}
          >
            <Radio value="user">
              按照用户{" "}
              <Tooltip title="多个子用户访问OSS，一般用作FTP文件管理">
                <QuestionCircleOutlined />
              </Tooltip>
            </Radio>
            <Radio value="ip" disabled>
              按照IP{" "}
              <Tooltip title="可公网读取的OSS">
                <QuestionCircleOutlined />
              </Tooltip>
            </Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item wrapperCol={buttonWrapperCol}>
          <Button
            loading={loading}
            type="primary"
            onClick={this.handleStatistics}
          >
            统计处理
          </Button>
        </Form.Item>
        <Table
          columns={this.getColumns()}
          dataSource={result}
          rowKey={(item, index) => index}
          loading={loading}
          pagination={false}
        />
      </div>
    );
  }
}
